import React, { useState, useEffect } from 'react';
import { getReferenceScripts } from '../../services/api';
import { ChevronRight, Check } from 'lucide-react';

interface ReferenceScript {
  script_id: number;
  title: string;
  version: number;
  content?: string;
}

interface ReferenceGalleryProps {
  userId: number;
  onScriptSelect: (scriptId: number, title: string, content: string) => void;
  onSelectionChange?: (selectedIds: number[]) => void;
}

const ReferenceGallery: React.FC<ReferenceGalleryProps> = ({ userId, onScriptSelect, onSelectionChange }) => {
  const [scripts, setScripts] = useState<ReferenceScript[]>([]);
  const [loading, setLoading] = useState(false);
  const [showAll, setShowAll] = useState(false);
  const [selectedScriptIds, setSelectedScriptIds] = useState<number[]>([]);

  useEffect(() => {
    const fetchScripts = async () => {
      setLoading(true);
      try {
        const response = await getReferenceScripts(userId);
        if (response.data.code === 200) {
          const scriptsData = Array.isArray(response.data.data) 
            ? response.data.data 
            : (response.data.data.scripts || []);
          setScripts(scriptsData);
        }
      } catch (error) {
        console.error('Error fetching reference scripts:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchScripts();
  }, [userId]);

  const handleScriptClick = (script: ReferenceScript) => {
    const newSelectedIds = selectedScriptIds.includes(script.script_id)
      ? selectedScriptIds.filter(id => id !== script.script_id)
      : [...selectedScriptIds, script.script_id];
    
    setSelectedScriptIds(newSelectedIds);
    
    if (onSelectionChange) {
      onSelectionChange(newSelectedIds);
    }
  };

  const handleScriptDoubleClick = (script: ReferenceScript) => {
    const content = script.content || '';
    onScriptSelect(script.script_id, script.title, content);
  };

  const displayedScripts = showAll ? scripts : scripts.slice(0, 5);

  return (
    <div className="relative">
      <div className="flex justify-between items-center mb-6">
        {scripts.length > 5 && (
          <button
            onClick={() => setShowAll(!showAll)}
            className="flex items-center text-ink-blue hover:text-ink-blue/80 transition-colors duration-300 font-merriweather text-sm"
          >
            {showAll ? '收起' : '查看更多'}
            <ChevronRight size={16} className={`ml-1 transition-transform duration-300 ${showAll ? 'rotate-90' : ''}`} />
          </button>
        )}
      </div>

      {loading ? (
        <div className="flex justify-center py-12">
          <div className="relative w-12 h-12">
            <div className="absolute inset-0 rounded-full border-2 border-paper-dark/20 animate-spin"></div>
            <div className="absolute inset-0 rounded-full border-t-2 border-ink-blue animate-spin" style={{ animationDuration: '1s' }}></div>
          </div>
        </div>
      ) : (
        <div className="overflow-x-auto pb-4 -mx-4 px-4">
          <div className="flex space-x-6 min-w-max">
            {displayedScripts.map((script, index) => (
              <div
                key={script.script_id}
                onClick={() => handleScriptClick(script)}
                onDoubleClick={() => handleScriptDoubleClick(script)}
                className={`w-56 paper-card p-4 cursor-pointer transform transition-all duration-300 hover:shadow-float hover:-translate-y-1 relative ${
                  selectedScriptIds.includes(script.script_id) ? 'ring-2 ring-ink-blue' : ''
                }`}
                style={{
                  transform: `rotate(${Math.sin(index * 0.5) * 3}deg)`,
                  transformOrigin: 'bottom center'
                }}
              >
                {selectedScriptIds.includes(script.script_id) && (
                  <div className="absolute top-2 left-2 w-6 h-6 bg-ink-blue rounded-full flex items-center justify-center z-10">
                    <Check size={14} className="text-paper" />
                  </div>
                )}
                <div className="absolute top-0 right-0 w-8 h-8 bg-ink-red/10 rounded-bl-lg flex items-center justify-center">
                  <span className="text-xs font-merriweather text-ink-red">{script.version}</span>
                </div>
                <h3 className="font-playfair text-ink text-lg mb-2 line-clamp-2 min-h-[3.5rem]">{script.title}</h3>
                <div className="h-24 bg-paper-dark/10 rounded p-2 text-xs font-inter text-ink/70 overflow-hidden relative">
                  <div className="absolute inset-0 bg-gradient-to-b from-transparent via-transparent to-paper-light/80"></div>
                  <p className="line-clamp-6">{script.content || '暂无内容'}</p>
                </div>
                <div className="mt-3 text-center">
                  <button 
                    onClick={(e) => {
                      e.stopPropagation();
                      handleScriptDoubleClick(script);
                    }}
                    className="text-xs font-merriweather text-ink-blue hover:underline"
                  >
                    查看全文
                  </button>
                </div>
              </div>
            ))}

            {displayedScripts.length === 0 && (
              <div className="col-span-full text-center py-12 text-ink/50 font-merriweather italic">
                暂无参考脚本
              </div>
            )}
          </div>
        </div>
      )}

      {/* Selected scripts count */}
      {selectedScriptIds.length > 0 && (
        <div className="mt-4 text-sm font-merriweather text-ink-blue">
          已选择 {selectedScriptIds.length} 个参考脚本
        </div>
      )}
    </div>
  );
};

export default ReferenceGallery;
